<script setup lang="ts">
import { onMounted, reactive } from 'vue'
import { Queue } from '../utils/Queue'

const emit = defineEmits(['transform-emoji'])
const historyEmojiList: number[] = reactive([]) // 获取最近使用的 Emoji
let resentEmoji

onMounted(() => {
  const recentEmoji = localStorage.getItem('resentEmoji')
  if (recentEmoji) {
    resentEmoji = new Queue(JSON.parse(recentEmoji), 16)
  } else {
    resentEmoji = new Queue(new Array<number>(), 16)
  }
  updateHistoryEmojiList(resentEmoji.getElements())

  // resentEmoji = localStorage.getItem('resentEmoji') ?
  //   new Queue(JSON.parse(localStorage.getItem('resentEmoji')), 16) : new Queue(new Array<number>(), 16)
  // updateHistoryEmojiList(resentEmoji.getElements())
})

const transformEmoji = (emoji) => {
  emit('transform-emoji', emoji)
}

const handleResentEmojiChoose = (index) => {
  resentEmoji.push(index)
  updateHistoryEmojiList(resentEmoji.getElements())
  localStorage.setItem('resentEmoji', JSON.stringify(historyEmojiList))
}

const updateHistoryEmojiList = (arrs: Array<number>) => {
  historyEmojiList.splice(0)
  arrs.forEach((item: number) => {
    historyEmojiList.push(item)
  })
}

const handleEmojiChoose = (index) => {
  const imgTag = `<img class="h-7 w-7 inline" src="../../resources/gif/${index}.gif" alt="">`
  transformEmoji(imgTag)
  handleResentEmojiChoose(index)
}
</script>

<template>
  <div class="w-full h-80 pb-15 overflow-auto box-border">
    <!-- 最近使用 -->
    <div v-if="historyEmojiList.length">
      <div class="text-xs mt-2.5 mr-0 mb-1">最近使用</div>
      <div class="w-full flex flex-wrap">
        <div
          v-for="(item, index) in historyEmojiList"
          :key="index"
          class="w-8 h-8 mt-1 mb-1 ml-2.5 mr-2.5 cursor-pointer"
        >
          <img
            width="100%"
            height="100%"
            :src="`../../resources/gif/${item}.gif`"
            alt=""
            @click="handleEmojiChoose(item)"
          />
        </div>
      </div>
    </div>

    <!-- 所有表情列表 -->
    <div class="text-xs mt-2.5 mr-0 mb-1">Emoji</div>
    <div class="w-full flex flex-wrap">
      <div
        v-for="(item, index) in 203"
        :key="index"
        class="w-8 h-8 mt-1 mb-1 ml-2.5 mr-2.5 cursor-pointer"
      >
        <img
          width="100%"
          height="100%"
          :src="`../../resources/gif/${item}.gif`"
          alt=""
          @click="handleEmojiChoose(item)"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
::-webkit-scrollbar {
  display: none;
}
</style>
